﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Media;
using ICSharpCode.AvalonEdit.CodeCompletion;
using ICSharpCode.AvalonEdit.Document;
using ICSharpCode.AvalonEdit.Editing;
using ICSharpCode.AvalonEdit.Highlighting;
using ICSharpCode.AvalonEdit.Search;

using JhEngine.Helpers;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using JHECIS.InterfaceTool.ViewModel;

namespace JhEngine
{
    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
            MainWindowViewModel model = new MainWindowViewModel();
            DataContext = model;
            this.model = model;

            txtScriptCode.TextArea.TextEntered += TextArea_TextEntered;
            SearchPanel.Install(this.txtScriptCode.TextArea);
            SearchPanel.Install(this.txtConvertResult.TextArea);
            SearchPanel.Install(this.txtInJson.TextArea);
            SearchPanel.Install(this.txtOutJson.TextArea);

            using (var stream = typeof(MainWindow).Assembly.GetManifestResourceStream("JhEngine.AutoComplete.AutoComplete.json"))
            {
                using (var reader = new StreamReader(stream, Encoding.UTF8))
                {
                    string value = reader.ReadToEnd();
                    autoCompletes = JsonConvert.DeserializeObject<List<AutoComplete>>(value);
                }
            }
        }

        private CompletionWindow _completionWindow;
        private readonly List<AutoComplete> autoCompletes = new List<AutoComplete>();
        private readonly MainWindowViewModel model;


        private void TextArea_TextEntered(object sender, TextCompositionEventArgs e)
        {
            ShowCompleteWindow(e.Text);
        }

        private void ShowCompleteWindow(string text, bool show = false)
        {
            try
            {
                if (show || text == "." || (autoCompletes?.Any(a => a.Key.Equals(text)) ?? false))
                {
                    if (_completionWindow == null)
                    {
                        _completionWindow = new CompletionWindow(txtScriptCode.TextArea);
                        _completionWindow.Closed += delegate
                        {
                            _completionWindow = null;
                        };
                    }
                    var data = _completionWindow.CompletionList.CompletionData;

                    autoCompletes.ForEach(a =>
                    {
                        a.Value.ForEach(b =>
                        {
                            if (!data.Any(c => c.Content.ToString() == b))
                            {
                                data.Add(new MyCompletionData(b, text));
                            }
                        }
                        );
                    });
                    model.InAutoComplete?.ForEach(a =>
                    {
                        if (!data.Any(c => c.Content.ToString() == a))
                        {
                            data.Add(new MyCompletionData(a, text));
                        }
                    });
                    if (data.Any())
                    {
                        if (_completionWindow != null)
                        {
                            _completionWindow.Show();
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                _completionWindow = null;
#if DEBUG
                LogHelper.GetLogHelper().Error(ex);
#endif
            }
        }

        private void btnComment_Click(object sender, System.Windows.RoutedEventArgs e)
        {
            if (!string.IsNullOrEmpty(txtScriptCode.SelectedText))
            {
                var code = txtScriptCode.SelectedText.Split('\n');
                txtScriptCode.SelectedText = string.Join(Environment.NewLine, code.Select(a => "//    " + a));
            }
        }

        private void btnUnComment_Click(object sender, System.Windows.RoutedEventArgs e)
        {
            if (!string.IsNullOrEmpty(txtScriptCode.SelectedText))
            {
                var code = txtScriptCode.SelectedText.Split('\n');
                txtScriptCode.SelectedText = string.Join(string.Empty, code.Select(a => a.Replace("//", string.Empty)));
            }
        }

        private void CommandBinding_Executed(object sender, ExecutedRoutedEventArgs e)
        {
            ShowCompleteWindow(string.Empty, true);
        }
    }

    internal class AutoComplete
    {
        public string Key { get; set; }
        public List<string> Value { get; set; }
    }

    public class MyCompletionData : ICompletionData
    {
        public MyCompletionData(string text, string activeText)
        {
            Text = text;
            ActiveText = activeText;
        }

        public string ActiveText { get; set; }
        public ImageSource Image => null;

        public string Text { get; }

        // Use this property if you want to show a fancy UIElement in the drop down list.
        public object Content => Text;

        public object Description => "Description for " + Text;

        public double Priority => 1;

        public void Complete(TextArea textArea, ISegment completionSegment, EventArgs insertionRequestEventArgs)
        {
            if (ActiveText.Equals(".") || string.IsNullOrEmpty(ActiveText))
            {
                textArea.Document.Replace(completionSegment, Text);
            }
            else
            {
                textArea.Document.Replace(completionSegment.Offset - 1, completionSegment.Length + 1, Text);
            }
        }
    }
}

